from lagent.actions import BaseAction
from lagent.schema import ActionReturn, ActionStatusCode
from lagent.schema import ActionStatusCode
import requests

class WeatherAPIAction(BaseAction):
    """调用天气API的动作类"""
    
    name = "weather_api"  # 添加动作名称

    def run(self, city: str) -> ActionReturn:
        """
        获取指定城市的天气信息

        Args:
            city (str): 城市名称

        Returns:
            ActionReturn: 包含天气信息的返回对象
        """
        tool_return = ActionReturn(type=self.name)
        try:
            # 调用外部天气API
            # 自行在高德地图官网注册，然后申请免费的API使用。
            # 链接如下：https://lbs.amap.com/
            response = requests.get(f"https://restapi.amap.com/v3/weather/weatherInfo?city={city}&key=4af023c68d48cc5e07103bb0a2d115b5")
            response.raise_for_status()
            data = response.json()
            # 提取天气信息
            weather_info = data['lives'][0]
            tool_return.result = [{'type': 'text', 'content': weather_info}]
            tool_return.state = ActionStatusCode.SUCCESS
        except Exception as e:
            tool_return.errmsg = str(e)
            tool_return.state = ActionStatusCode.API_ERROR
        return tool_return
